package com.honghu.villagepost.activity

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.ToastUtils
import com.honghu.villagepost.R
import com.honghu.villagepost.activity.AddAddrActivity
import com.honghu.villagepost.adapter.AddrAdapter
import com.honghu.villagepost.api.ApiService
import com.honghu.villagepost.base.BaseListActivity
import com.honghu.villagepost.callback.DialogCallback
import com.honghu.villagepost.callback.LzyResponse
import com.honghu.villagepost.constant.Constants
import com.honghu.villagepost.entity.Addr
import com.lzy.okgo.model.Response
import kotlinx.android.synthetic.main.search_refresh_layout_list.*
import org.greenrobot.eventbus.EventBus

/**
 * @author: mqwang
 * @create: 2/10/21 12:07 AM
 * @Description: 收货地址列表
 */
class AddrActivity : BaseListActivity<Addr>() {

    private val EDIT_REQUEST_CODE = 1

    private val addrAdapter: AddrAdapter by lazy {
        AddrAdapter()
    }

    companion object{
        fun self(context: Context, isSelect: Boolean){
            val intent = Intent(context, AddrActivity::class.java)
            intent.putExtra(Constants.IS_SELECT, isSelect)
            context.startActivity(intent)
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.search_refresh_layout_list
    }

    override fun bindRecyclerView(recLv: RecyclerView?) {
        recLv!!.adapter = addrAdapter
        setMainTitle("地址列表")
        setSubTitle("添加")

        et_search.addTextChangedListener(object : TextWatcher{
            override fun afterTextChanged(s: Editable?) {
                onRefresh(refreshLayout)
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

        })
        et_search.setOnEditorActionListener(TextView.OnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                onRefresh(refreshLayout)
                return@OnEditorActionListener true
            }
            false
        })

        var isSelect = intent.getBooleanExtra(Constants.IS_SELECT, false)
        addrAdapter.setOnItemClickListener { adapter, view, position ->
            var addr = addrAdapter.getItem(position) as Addr
            if (isSelect){
                EventBus.getDefault().post(addr)
                finish()
            }
        }
        addrAdapter.setOnItemChildClickListener { adapter, view, position ->
            var addr = adapter.data.get(position) as Addr
            when (view.id) {
                R.id.tv_edit -> {
                    AddAddrActivity.self(this, addr, EDIT_REQUEST_CODE)
                }
                R.id.tv_delete -> {
                    ApiService.user_address_delete(this, addr.id, object : DialogCallback<LzyResponse<Any>>() {
                        override fun onSuccess(response: Response<LzyResponse<Any>>?) {
                            notifyRemove(addr)
                            ToastUtils.showShort(getString(R.string.success))
                        }
                    })
                }
            }
        }

    }

    private fun notifyRemove(addr: Addr) {
        val data = addrAdapter.data
        for (i in 0..data.size-1){
            val item = data.get(i)
            if (item.id == addr.id){
                data.removeAt(i)
                addrAdapter.notifyItemRemoved(i)
                return
            }
        }
    }

    override fun onRightClickAction() {
        super.onRightClickAction()
        ActivityUtils.startActivityForResult(this, AddAddrActivity::class.java, EDIT_REQUEST_CODE)
    }

    override fun loadData(page: Int, pageCount: Int) {
        val searchKey = et_search.text.toString()
        ApiService.user_address(this, searchKey, page, object : DialogCallback<LzyResponse<Addr>>() {
            override fun onSuccess(response: Response<LzyResponse<Addr>>?) {
                val records = response!!.body().data.records
                onGetDataSuc(records)
            }
        })
    }

    override fun getData(): MutableList<Addr> {
        return addrAdapter.data
    }

    override fun bindData(isRefresh: Boolean, list: MutableList<Addr>?) {
        when (isRefresh) {
            true -> {
                addrAdapter.setNewData(list)
            }
            false -> {
                addrAdapter.addData(list!!)
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == EDIT_REQUEST_CODE){
            if (resultCode == Activity.RESULT_OK){
                onRefresh(refreshLayout)
            }
        }
    }
}